package com.tnl.app.controller;


import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.jfinal.weixin.sdk.utils.HttpUtils;
import com.jfinal.wxaapp.WxaConfig;
import com.jfinal.wxaapp.api.WxaAccessToken;
import com.jfinal.wxaapp.api.WxaAccessTokenApi;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.tnl.app.config.GlobalConfig;
import com.tnl.app.entity.AccessToken;
import com.tnl.base.web.JsonController;
import com.tnl.utils.UserManagerUtil;
import com.tnl.utils.WxaTemplateUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/wechat")
public class WeChatQRCodeController extends JsonController {

    private static final String url = "https://api.weixin.qq.com/wxa/getwxacode?access_token=%s";

    @RequestMapping(value = "/qrcode/{positionId}", method = RequestMethod.GET)
    @ResponseBody
    public void getQRCode(@PathVariable Long positionId, HttpServletRequest request, HttpServletResponse response) throws IOException {
        DefaultPutRet putRet = null;
        String fileName = "position_".concat(positionId.toString()).concat(".png");
        WxaAccessToken accessToken = WxaAccessTokenApi.refreshAccessToken(WxaTemplateUtil.getApiConfigYiRenCai());
        String token = accessToken.getAccessToken();
        final String qrCodeUrl = String.format(url, token);
        Configuration cfg = new Configuration(Zone.zone0());
        UploadManager uploadManager = new UploadManager(cfg);
        Map map = new HashMap<>();
        map.put("path", "pages/position-detail/position-detail?pid="+positionId);
        map.put("is_hyaline", true);
        InputStream result = HttpUtils.download(qrCodeUrl, JSONObject.toJSONString(map));
        byte[] bytes = this.readStream(result);
        ByteArrayInputStream byteInputStream = new ByteArrayInputStream(bytes);

        Auth auth = Auth.create(GlobalConfig.QNACCESS_KEY, GlobalConfig.QNSECRET_KEY);
        String upToken = auth.uploadToken(GlobalConfig.BUCKET_MEDTREND);
        Response res = uploadManager.put(byteInputStream, fileName, upToken, null, null);
        //解析上传成功的结果
        putRet = new Gson().fromJson(res.bodyString(), DefaultPutRet.class);
        System.out.println(putRet.key);
        System.out.println(putRet.hash);
        String qrCode = GlobalConfig.FILE_PREFIX_PATH + putRet.key;
        this.successJson(qrCode, "职位二维码", response);
    }

    private byte[] readStream(InputStream inStream) throws IOException {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = -1;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        outStream.close();
        inStream.close();
        return outStream.toByteArray();

    }
    
    @RequestMapping(value = "getBackground", method = RequestMethod.GET)
    @ResponseBody
    public void getBackground(HttpServletResponse response) {
    	String uri = "https://tiaonali.com/position_background.png";
    	this.successJson(uri, "背景图uri", response);
    }

}
